import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/train/model/train_stream.dart';
import 'package:flutter_learn_vi/src/page/train/train_header_time_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_start_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/16.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///教师点击开始上课
class TrainTeacherStartWidget extends StatefulWidget {
  final TrainApproveBean approveBean;

  const TrainTeacherStartWidget({Key key, this.approveBean}) : super(key: key);

  @override
  _TrainTeacherStartWidgetState createState() =>
      _TrainTeacherStartWidgetState();
}

class _TrainTeacherStartWidgetState extends State<TrainTeacherStartWidget>
    with TrainModel {
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    getTeacherCourseIng();

    _streamSubscription = trainStream.stream.listen((TrainEventBean event) {
      if (event.statues == 2) {
        getTeacherCourseIng();
      }
    });
  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        padding: EdgeInsets.only(left: 12, right: 12, bottom: 6),
        child: Card(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.only(top: 10),
                  child: buildHeader(),
                ),
                startCourse(),
              ],
            ),
          ),
        ));
  }

  Widget startCourse() {
    if (_isLoading) {
      return LoadingWidget();
    }

    Color color = Color(0xff37967f);
    if (_courseBean != null) {
      color = Color(0xff1b83c9);
    }
    return buildClipOval(color);
  }

  Widget buildClipOval(color) {
    return Container(
      margin: EdgeInsets.only(top: 22, bottom: 22),
      child: ClipOval(
        child: Material(
          color: color,
          child: InkWell(
            onTap: () {
              if (_courseBean != null) {
                coursFinishCheckFunction();
              } else {
                NavigatorUtils.pushPage(
                    context,
                    TrainTeacherSelectCoursePage(
                      approveBean: widget.approveBean,
                    ), callback: (value) async {
                  if (value != null) {
                    //查询是否有正在开始的课程
                    await getTeacherCourseIng();
                    //数据状态
                    _courseBean.studyStatues = 0;
                    //发送消息刷新
                    trainStream.add(TrainEventBean(0, _courseBean));
                  }
                });
              }
            },
            child: Container(
              alignment: Alignment.center,
              width: 120,
              height: 120,
              child: Text(
                _courseBean != null ? "下课" : "上课",
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  buildHeader() {
    if (_courseBean == null) {
      return TrainHeaderTimerWidget();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("当前时间")),
                SizedBox(
                  width: 8,
                ),
                TrainHeaderTimerWidget(),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("开始时间")),
                SizedBox(
                  width: 8,
                ),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/time_icon.png",
                      width: 18,
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text("${_courseBean.startTime}"),
                  ],
                ),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("已上课程时间")),
                SizedBox(
                  width: 8,
                ),
                TrainHeaderTimerWidget(startTime: _courseBean.startTime),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Text("当前正在进行的课程"),
          ],
        ),
        Row(
          children: [
            Expanded(
                child: Text(
                    "${_courseBean.courseName}->${_courseBean.courseName}")),
          ],
        )
      ],
    );
  }

  bool _isLoading = true;
  CourseBean _courseBean;

  //获取教师所有的课程
  Future<bool> getTeacherCourseIng() async {
    List<CourseBean> courseList =
        await getTeacherCourseNetDatils(widget.approveBean.trainId);
    _isLoading = false;
    if (courseList != null && courseList.length > 0) {
      _courseBean = courseList[0];
    } else {
      _courseBean = null;
    }
    if (mounted) {
      setState(() {});
    }
    return Future.value(true);
  }

  void coursFinishCheckFunction() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定下课吗??",
        selectCallBack: () {
          _courseBean.studyStatues = 1;
          //发送消息刷新
          trainStream.add(TrainEventBean(0, _courseBean));
          coursFinishRequest();
        });
  }

  void coursFinishRequest() async {
    setState(() {
      _isLoading = true;
    });
    await coursFinishRequestFunction(_courseBean, widget.approveBean.trainId);
    await getTeacherCourseIng();
    setState(() {
      _isLoading = false;
    });
  }
}
